from django.shortcuts import render, HttpResponse
# 引入操作数据库的通用模块
from utils import sqlhelper
# 引入JsonResponse
from django.http import JsonResponse
# 导入时间日期的模块
from datetime import datetime
# 导入爬取天气的类
from spiderweb.classes import spiderweather



def spider_weather(request):
    """展示爬取天气的页面"""
    return render(request, 'spiderweather.html')


def get_spider_weather_log(request):
    """获取爬取天气的日志"""
    # 准备获取数据的sql
    sql = "Select  Date,SpiderStatus, SpiderNumber, UpdateNumber, InsertNumber " \
          "from SpiderWeather Order By DATE DESC"
    # 获取数据并转为dict
    response = sqlhelper.get_db_data_dict(sql, ['date', 'status', 'spider', 'update', 'insert'])
    # 把日期格式化 yyyy-mm-dd HH:MM:SS
    for one in response['data']:
        one['date'] = one['date'].strftime('%Y-%m-%d %H:%M:%S')

    # 返回数据
    return JsonResponse({'code':0 , 'msg': response['error'], 'data': response['data']})


def start_spider(request):
    """开始爬取天气"""
    # 实例化一个操作对象
    spider_obj = spiderweather.CityWeather()
    # 获取url
    spider_obj.get_urls_from_db()
    # 爬取天气
    spider_obj.get_weather_from_url()
    # 写入数据库
    spider_obj.save_weather_db()
    # 获取爬取的结果
    res = spider_obj.res
    # 把爬取的结果写入到数据库
    sql = "Insert Into SpiderWeather (Date, SpiderStatus, SpiderNumber, UpdateNumber, InsertNumber) " \
          "Values('%s','%s','%s','%s','%s')" %(res['date'], res['status'], res['spider'], res['update'],
                                               res['insert'])
    # 运行
    response = sqlhelper.update_db(sql)
    # 判断
    if response['status']:
        return JsonResponse({'status': True})
    else:
        return JsonResponse({'status': False})



